package com.example.im.infra.executor.send;

import com.example.im.config.WebSocketProperties;
import com.example.im.infra.executor.config.ExecutorConfiguration;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * @author PC
 * 发送逻辑工厂
 */
@Component
public class SendExecutorFactory {

    private final WebSocketProperties webSocketProperties;

    private ExecutorConfiguration executorConfiguration;

    @Autowired
    public SendExecutorFactory(WebSocketProperties webSocketProperties) {
        this.webSocketProperties = webSocketProperties;
    }

    @Autowired
    public void setExecutorConfiguration(ExecutorConfiguration executorConfiguration) {
        this.executorConfiguration = executorConfiguration;
    }

    public void onMessage(String sendUserName, String message) {
        IBaseSendExecutor iBaseSendExecutor = Optional.ofNullable(executorConfiguration.getBaseSendExecutorMap()
                .get(webSocketProperties.getCommunicationType())).orElse(new DefaultSendExecutor());
        //包含@发给指定人，否则发给全部人
        if (StringUtils.contains(message, webSocketProperties.getReceiverSeparator())) {
            iBaseSendExecutor.sendToUser(sendUserName, message);
        } else {
            iBaseSendExecutor.sendToAll(sendUserName, message);
        }
    }
}
